package com.wedistudio.android.framework.fetcher;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.wedistudio.android.framework.json.JSonObject;

public class URLParams extends JSonObject<URLParams> {
	private URL url;
	private Map<String, String> params;

	public static URLParams create(URL url) {
		return new URLParams(url);
	}

	private URLParams(URL url) {
		super();
		this.url = url;
		params = Collections.emptyMap();
	}

	public void addParam(String key, String value) {
		if (params.isEmpty())
			params = new HashMap<String, String>();
		params.put(key, value);
	}

	public URL getUrl() {
		return url;
	}

	public Map<String, String> getParams() {
		return params;
	}

	public String toURL() {
		List<NameValuePair> getParameters = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			getParameters.add(new BasicNameValuePair(entry.getKey(), entry
					.getValue()));
		}

		String urlWithParams = url.toString()
				+ (getParameters.size() > 0 ? "?" : "")
				+ URLEncodedUtils.format(getParameters, "utf-8");

		return urlWithParams;
	}
}
